package com.wn.controller;

import com.alibaba.fastjson.JSON;
import com.wn.bean.R;
import com.wn.bean.Student;
import com.wn.service.StudentService;
import com.wn.service.impl.StudentServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @author yellow Docter
 * @date 2022 -06-30
 * @desc
 */
@WebServlet("/updateStu")
public class UpdateStuServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("text/html;charset=utf-8");

        // 01 拿到数据
        Map<String, String[]> map = req.getParameterMap();
        Student student = new Student();
        try {
            BeanUtils.populate(student,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        System.out.println("student = " + student);

        // 02 调用业务
        StudentService studentService = new StudentServiceImpl();
        boolean flag = studentService.update(student);
        // 03 回写数据

        String jsonString = JSON.toJSONString(flag ? R.ok() : R.error());
        resp.getWriter().write(jsonString);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
